package com.martin.lib_base.ktx

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import dev.DevUtils

/**
 * @author：孟凡华
 * @date：2022/11/11
 * @desc：Context拓展
 */

fun requireContext(): Activity = DevUtils.getTopActivity()

/**
 * 根据Context来关闭Activity
 */
fun Context.finish() {
    getActivity().finish()
}

/**
 * 获取context对应的Activity
 */
fun Context.getActivity(): Activity {
    if (this is Activity) {
        return this
    } else if (this is Fragment) {
        return requireActivity()
    }
    return DevUtils.getTopActivity()
}

/**
 * 获取生命周期持有者
 */
fun Context.getLifecycleOwner(): LifecycleOwner {
    return when (this) {
        is LifecycleOwner -> {
            this
        }

        else -> {
            return DevUtils.getTopActivity() as AppCompatActivity
        }
    }
}